import { NavLink, Route, Switch } from 'react-router-dom'
import AuthDemo from './views/AuthDemo'
import CarouselDemo from './views/CarouselDemo'
import CarsDemo from './views/CarsDemo'
import ContextDemo from './views/ContextDemo'
import Home from './views/Home'
import ListReducerDemo from './views/ListReducerDemo'
import MemoAndCallbackDemo from './views/MemoAndCallbackDemo'
import MyBigListDemo from './views/MyBigListDemo'
import PromiseDemo from './views/PromiseDemo'
import ReducerDemo from './views/ReducerDemo'
import RenderDemo from './views/RenderDemo'
import Stopwatch from './views/Stopwatch'
import TodoApp from './views/TodoApp'
import UserApp from './views/UserApp'
import UserLogin from './views/UserLogin'

const routes = [
  {
    path: '/',
    text: '首页',
    exact: true,
    component: Home
  },
  {
    path: '/render-demo',
    text: '渲染机制',
    component: RenderDemo
  },
  {
    path: '/memo-callback',
    text: 'memo和callback',
    component: MemoAndCallbackDemo
  },
  {
    path: '/big-list',
    text: 'MyBigListDemo',
    component: MyBigListDemo
  },
  {
    path: '/reducer-demo',
    text: 'Reducer',
    component: ReducerDemo
  },
  {
    path: '/stopwatch',
    text: '计时器',
    component: Stopwatch
  },
  {
    path: '/todo-app',
    text: 'todo app',
    component: TodoApp
  },
  {
    path: '/list-demo',
    text: 'list demo',
    component: ListReducerDemo
  },
  {
    path: '/user-login',
    text: 'user login',
    component: UserLogin
  },
  {
    path: '/context-demo',
    text: '上下文',
    component: ContextDemo
  },
  {
    path: '/cars-demo',
    text: 'cars',
    component: CarsDemo
  },
  {
    path: '/promise-demo',
    text: 'promise',
    component: PromiseDemo
  },
  {
    path: '/user-app',
    text: 'user-app',
    component: UserApp
  },
  {
    path: '/auth',
    text: 'auth demo',
    component: AuthDemo
  },
  {
    path: '/carousel',
    text: '轮播图',
    component: CarouselDemo
  }
]

export default routes

export const makeRoutes = (routes, parentPath = '') => {
  return routes.map(({ component: View, subRoutes, path, ...route }) => {
    const currentPath = parentPath + path
    return (
      <Route key={currentPath} path={currentPath} {...route}>
        <Switch>
          {subRoutes && makeRoutes(subRoutes, currentPath)}
          <Route path={currentPath}>
            <View />
          </Route>
        </Switch>
      </Route>
    )
  })
}

export const makeNavLinks = (routes, parentPath = '') => {
  return (
    <ul>
      {routes.map(({ text, path, subRoutes }) => {
        const currentPath = parentPath + path
        return (
          <li key={currentPath}>
            <NavLink to={currentPath} exact>
              {text}
            </NavLink>
            {subRoutes && makeNavLinks(subRoutes, currentPath)}
          </li>
        )
      })}
    </ul>
  )
}
